package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"log"
	"kubeInstall/conf"
	"time"
)

var db *gorm.DB

func init() {
	// init db
	var err error
	db, err = gorm.Open(conf.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local",
		conf.DatabaseSetting.User,
		conf.DatabaseSetting.Password,
		conf.DatabaseSetting.Host,
		conf.DatabaseSetting.Name))

	if err != nil {
		log.Fatalf("models.Setup err: %v", err)
	}

	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return conf.DatabaseSetting.TablePrefix + defaultTableName
	}

	db.DB().SetMaxIdleConns(10)
	db.DB().SetMaxOpenConns(100)

	// 启用Logger，显示详细日志
	db.LogMode(true)

	// 自动创建表根据结构体名和字段，自动生成。
	db.AutoMigrate(&Host{}, &SysPackage{}, &DockerImage{}, &Cluster{})
}

// CloseDB closes database connection (unnecessary)
func CloseDB() {
	defer db.Close()
}

type BaseModel struct {
	CreatedAt time.Time
	UpdatedAt time.Time
}
